package com.huawei.boss.lang;

import java.io.IOException;
import java.lang.reflect.Field;

public class Systems {
    public static final String MODEL = System.getProperty("sun.arch.data.model");
    /**
     * 动态修改java.library.path变量<br/>
     * 这种实现的局限性，和jvm的实现强关联，只要jvm实现不是用的变量usr_paths来保存java.library.path的值，这个方法就不能用了。
     * 
     * @param path 修改添加路径
     * @throws IOException
     * 
     * @see http://chiefleo.me/archives/439 动态设置java.library.path
     * @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4280189 java.library.path只在jvm启动时读取一次
     */
    public static void addJavaLibpath(String path) throws IOException {
        try {
            Field field = ClassLoader.class.getDeclaredField("usr_paths");
            field.setAccessible(true);
            String[] paths = (String[]) field.get(null);
            for (int i = 0; i < paths.length; i++) {
                if (path.equals(paths[i])) {
                    return;
                }
            }
            String[] tmp = new String[paths.length + 1];
            System.arraycopy(paths, 0, tmp, 0, paths.length);
            tmp[paths.length] = path;
            field.set(null, tmp);
        } catch (IllegalAccessException e) {
            throw new IOException("Failed to get permissions to set library path");
        } catch (NoSuchFieldException e) {
            throw new IOException("Failed to get field handle to set library path");
        }
    }

    /**
     * 判断是否64位虚拟机环境
     * @return 是64位返回true,否则返回false
     */
    public static boolean is64BitEnv() {
        return "64".equals(MODEL);
    }
}
